package com.cwits.wifi.ui.activity;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwits.wifi.R;
import com.cwits.wifi.tool.FileUtil;
import com.cwits.wifi.util.PreferenceUtils;
import com.cwits.wifi.util.PreferencesHelper;
import com.igexin.sdk.PushManager;

import java.io.File;
import java.util.Collections;
import java.util.List;

import io.vov.vitamio.Vitamio;

public class SplishActivity extends Activity implements View.OnClickListener {

    private ProgressDialog pd;
    private Button mBtn;
    private ImageView mIvPassword;
    private EditText mEtPassword;
    private boolean mAutoIs;
    private boolean CHANGEFILE = false;

    private String pkg;
    private String cls;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_splish);
        mBtn = (Button) findViewById(R.id.splish_btn);
        mBtn.setOnClickListener(this);
        mIvPassword = (ImageView) findViewById(R.id.iv_password);
        mIvPassword.setOnClickListener(this);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        /*
        if(isExistNewApp()){
            showNewappInfo();
            return;
        }
        */
        if (PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getBoolean("is_getui", false)) {
            Intent infoIntent = new Intent(this.getApplication(), MyInfoActivity.class);
            infoIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(infoIntent);
            PreferencesHelper.putBooleanValue(this.getApplicationContext(), "is_getui", false);
            finish();
        } else {
            mAutoIs = true;

            /*lihaoran 1478133390@qq.com
             *GeTui.com for intialize GeTui_SDK start
             */
            /*GeTui.com for intialize GeTui_SDK end*/

            PushManager.getInstance().initialize(this.getApplicationContext());
            String cid = PreferencesHelper.getSharedPreferences(this.getApplicationContext()).getString("cid", "");
            if (cid.equals("")) {
                cid = PushManager.getInstance().getClientid(this.getApplicationContext());
                if (cid != null && cid.equals("") == false)
                    PreferencesHelper.putStringValue(this.getApplicationContext(), "cid", cid);
            }

            deleFile();
            handler.sendEmptyMessageDelayed(1001, 1000);
        }
        //Intent background = new Intent();
        //background.setClass(this, BackgroundGetDeviceDataService.class);
        //this.startService(background);

        findViewById(R.id.btn_login).setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Vitamio.initialize(SplishActivity.this, getResources().getIdentifier("libarm", "raw", getPackageName()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.splish_btn:
                v.setVisibility(View.GONE);
                mAutoIs = false;
                handler.sendEmptyMessageDelayed(1004, 50);
//                handler.sendEmptyMessage(1004);
                break;
            case R.id.btn_login:
                String account = ((EditText) findViewById(R.id.et_usernum)).getText().toString();
                String password = ((EditText) findViewById(R.id.et_password)).getText().toString();
                if (TextUtils.isEmpty(account)) {
                    Toast.makeText(getApplicationContext(), "请输入您的账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "请输入您的密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                PreferenceUtils.putString(getApplicationContext(), PreferenceUtils.ACCOUNT_INFO, account);
                toMain();
                break;
            case R.id.iv_password:
                if (!mIvPassword.isSelected()) {
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mEtPassword.setSelection(mEtPassword.getText().toString().length());
                } else {
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    mEtPassword.setSelection(mEtPassword.getText().toString().length());
                }
                mIvPassword.setSelected(!mIvPassword.isSelected());
                break;
        }
    }

    private void deleteFile(File file) {
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFile(files[i]);
            }
        }
        file.delete();
    }

    private void deleFile() {
        File tempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp");
        deleteFile(tempFile);
        File oldFile = new File(Environment.getExternalStorageDirectory().getPath() + "/理赔保记录仪");
        if (!oldFile.exists()) {
            CHANGEFILE = true;
            return;
        }

        File videoFile = new File(Environment.getExternalStorageDirectory().getPath() + "/理赔保记录仪/video");
        File photoFile = new File(Environment.getExternalStorageDirectory().getPath() + "/理赔保记录仪/photo");
        File toVideo = new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video");
        File toPhoto = new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
        if (!toVideo.exists()) {
            toVideo.mkdirs();
        }
        if (!toPhoto.exists()) {
            toPhoto.mkdirs();
        }

        File[] videoFiles = videoFile.listFiles();
        if (videoFiles != null) {
            for (int i = 0; i < videoFiles.length; i++) {
                FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/理赔保记录仪/video/" + videoFiles[i].getName()
                        , Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video");
            }
        }

        File[] photoFiles = photoFile.listFiles();
        if (photoFiles != null) {
            for (int i = 0; i < photoFiles.length; i++) {
                FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/理赔保记录仪/photo/" + photoFiles[i].getName()
                        , Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
            }
        }
        deleteFile(oldFile);
        CHANGEFILE = true;

    }

    private boolean isExistNewApp() {
        boolean flag = false;
        //应用过滤条件
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PackageManager mPackageManager = this.getApplicationContext().getPackageManager();
        List<ResolveInfo> mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
        //按报名排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));

        for (ResolveInfo res : mAllApps) {
            //该应用的包名和主Activity
            String pkgtemp = res.activityInfo.packageName;

            // 打开最新版本app
            if (pkgtemp.contains("com.cwits.CarDVR168")) {
                pkg = res.activityInfo.packageName;
                cls = res.activityInfo.name;
                flag = true;
                break;
            }
        }
        return flag;
    }

    private void startNewApp() {
        ComponentName componet = new ComponentName(pkg, cls);
        Intent intent = new Intent();
        intent.setComponent(componet);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }

    private void showNewappInfo() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(getApplicationContext(),
                R.layout.dialog_update, null);
        TextView remind = (TextView) view
                .findViewById(R.id.dialog_up_title);
        TextView msg_info = (TextView) view
                .findViewById(R.id.dialog_up_msg);
        TextView textview_cancle = (TextView) view
                .findViewById(R.id.dialog_up_canale);
        TextView textview_ok = (TextView) view
                .findViewById(R.id.dialog_up_ok);
        //remind.setText(getString(R.string.update) + verInfo.mVersionName);
        // msg_info.setText(R.string.update_remind);
        textview_cancle.setText(R.string.exit);
        textview_ok.setText(R.string.changetonew_ok);
        remind.setText(R.string.changetonew_title);
        msg_info.setText(R.string.changetonew_info);
        // RelativeLayout cancleRl = (RelativeLayout) view
        // .findViewById(R.id.dialog_del_ok);
        // RelativeLayout okRl = (RelativeLayout) view
        // .findViewById(R.id.dialog_del_cancle);

        builder.setView(view);

        final AlertDialog dialog = builder.create();

        textview_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dialog.dismiss();
                startNewApp();
                finish();

            }
        });

        textview_cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1001:
                    if (mAutoIs) {
                        mBtn.setText(R.string.skip2);
                        handler.sendEmptyMessageDelayed(1002, 1000);
                    }

                    break;
                case 1002:
                    if (mAutoIs) {
                        mBtn.setText(R.string.skip1);
                        handler.sendEmptyMessageDelayed(1003, 1000);
                    }
                    break;
                case 1003:
                    if (mAutoIs) {
                        mBtn.setText(R.string.skip0);
                        handler.sendEmptyMessageDelayed(1004, 50);
                    }
                    break;
                case 1004:
                    if (CHANGEFILE) {
                        //文件迁移完
                        if (null != pd && pd.isShowing())
                            pd.dismiss();
                        checkIsLogin();
                    } else {
                        //文件正在迁移
                        if (!pd.isShowing()) {
                            pd = ProgressDialog.show(SplishActivity.this, getString(R.string.dialog_tip), getString(R.string.delete_more_file));
                        }
                        handler.sendEmptyMessageDelayed(1004, 500);
                    }

                    break;
            }
        }
    };

    private void checkIsLogin() {
        if (TextUtils.isEmpty(PreferenceUtils.getString(getApplicationContext(), PreferenceUtils.ACCOUNT_INFO))) {
            findViewById(R.id.ll_login).setVisibility(View.VISIBLE);
            mBtn.setVisibility(View.GONE);
        } else {
            toMain();
        }
    }

    private void toMain() {
        Intent intent = new Intent(SplishActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(1001);
        handler.removeMessages(1002);
        handler.removeMessages(1003);
        handler.removeMessages(1004);
    }
}
